<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-09-29
 * Time: 13:48
 */

namespace backend\controllers;


use app\models\CtiFile;
use app\models\CtiZuoxi;
use common\helps\Tools;
use common\helps\UploadFiles;
use moonland\phpexcel\Excel;
use yii\helpers\ArrayHelper;

class CtiManagerZuoxiController  extends CtiManagerController
{

    /**
     * 导入网关文件里面的内容
     */
    public function actionUpload()
    {
        try{
            $model = new CtiFile();
            $file = $_FILES['file'];
            if (!empty($file)) {
                $count = CtiFile::find()->select("*")->where(["name"=>$file['name']])->count();
                $model->name = $file['name'];
                if ($count>0){//表面所上传的文件已经上传过了，
                    return "1";
                }
                $myfile = UploadFiles::common_upload_single($file);
                if(!empty($model->name) && $myfile){
                    //开启事务
                    $connection = \Yii::$app->getDb();
                    $transaction = $connection->beginTransaction();
                    //先保存表；
                    $getExel = Excel::import([
                        'file'=>$myfile['filepath'],
                    ]);
                    $model->type = "cti_Zuoxi";
                    $model->path = $this->https_url.$myfile['filename'];
                    $model->filesize = $file['size'];
                    $model->create_at = time();
                    $model->save();
                    $array_key = [
                        '坐席名称' => "name",
                        '坐席号码' => "number",
                        '坐席类型' => "type",
                        '坐席状态' => "status",
                        '最大不回复时间' => "max_no_answer",
                        '最大包裹时间' => "wrap_up_time",
                        '拒接后延迟时间' => "reject_delay_time",
                        '忙后延迟时间' => "busy_delay_time",
                        '等级' => "level",
                        '位置' => "position",
                    ];
                    $models = $model->find()->where('1=1')->orderBy('id desc')->one();
                    $id = $models->id;
                    foreach($getExel['file'] as $attributes)
                    {
                        foreach($attributes as $k=>$v)
                        {
                            $attributes_new[$array_key[$k]] = "".$v;
                        }
                        $CtiZuoxi = new CtiZuoxi();
                        $CtiZuoxi->file_id = $id;
                        $CtiZuoxi->create_at = time();
                        $CtiZuoxi->setAttributes($attributes_new);
                        $CtiZuoxi->save();
                    }
                    //更新导入了几条记录
                    $model->updateAttributes(['number'=>count($getExel['file'])]);
                    $transaction->commit();
                    //事务完成，一次性提交
                }
                return "true";
            }else{
                return "false";
            }
        }catch (\Exception $e){
            Tools::l($e);
        }
    }

    /**
     * 更新坐席的数据
     */
    public function actionUpdate(){
        if (isset($_POST['id'])){
            $id = $_POST['id'];
            $zuoxi = CtiZuoxi::findOne($id);
            $res = $zuoxi->updateAttributes($_POST);
            if ($res){
                //把坐席文件写到xml文件里面，然后刷新
                $res2 = $this->actionRegistZuoxiXml($id);
                if ($res2){//表明写入成功，可以重新刷新配置文件，将内容写到freeswitch数据库里面
                    $this->execFSBgapi("reload mod_callcenter");//最后执行以下更新freeswitch数据库
                    return json_encode(['data'=>'','res'=>1]);
                }else{
                    return json_encode(['data'=>'','res'=>0]);
                }
            }
        }else{
            $post = $_POST;
            $post['create_at'] = time();
            $zuoxi = new CtiZuoxi();
            $zuoxi->load(['CtiZuoxi'=>$post]);
            $res = $zuoxi->save();
        }
        return json_encode(['data'=>'','res'=>$res]);
    }

    /**
     * 把的坐席注册到  freeswitch中
     */
    public function actionRegistZuoxi($id){
        $zuoxi = CtiZuoxi::findOne($id);
        $post = ArrayHelper::toArray($zuoxi);
        //以下命令是暂时的改变状态数据，运行reload mod_callcenter就会重新加载xml里面的数据，将数据恢复到默认值
        //命令是刷新freeswitch里面的status,max_no_answer,reject_delay_time的参数，命令中间用 逗号, 隔开
        $cmd1 = 'callcenter_config agent set status '.$post['number'].'@${domain} \''.$post['status'].'\',';
        $cmd2 = 'callcenter_config agent set type '.$post['number'].'@${domain} \''.$post['type'].'\',';
        $cmd3 = 'callcenter_config agent set max_no_answer '.$post['number'].'@${domain} \''.$post['max_no_answer'].'\',';
        $cmd4 = 'callcenter_config agent set wrap_up_time '.$post['number'].'@${domain} \''.$post['wrap_up_time'].'\',';
        $cmd5 = 'callcenter_config agent set reject_delay_time '.$post['number'].'@${domain} \''.$post['reject_delay_time'].'\',';
        $cmd6 = 'callcenter_config agent set busy_delay_time '.$post['number'].'@${domain} \''.$post['busy_delay_time'].'\',';
        $cmd7 = 'callcenter_config tier set level support@default '.$post['number'].'@${domain} \''.$post['level'].'\',';
        $cmd8 = 'callcenter_config tier set position support@default '.$post['number'].'@${domain} \''.$post['position'].'\',';
        $cmd = $cmd1.$cmd2.$cmd3.$cmd4.$cmd5.$cmd6.$cmd7.$cmd8;
        return $this->execFSApi($cmd);
    }

    /**
     * 把的坐席注册到  freeswitch中，直接将数据库的内容写到freeswitch 的xml文件中
     */
    public function actionRegistZuoxiXml($id){
        $zuoxi = CtiZuoxi::findOne($id);
        $post = ArrayHelper::toArray($zuoxi);
        //将conf/auto_configs/callcenter.conf.xml配置文件里面的内容替换掉，
        $file = $this->path.'conf\\autoload_configs\\callcenter.conf.xml';
        $search1 = ['agents','agent','name="'.$post['number'].'@\\${domain}"','status="[\s\S]*"'];
        $replace1 = ['agents','agent','name="'.$post['number'].'@${domain}"','status="'.$post['status'].'"'];
        $res1 = $this->replaceXmlFileConfig($file,$search1,$replace1,false);
        $search2 = ['agents','agent','name="'.$post['number'].'@\\${domain}"','type="[\s\S]*"'];
        $replace2 = ['agents','agent','name="'.$post['number'].'@${domain}"','type="'.$post['type'].'"'];
        $res2 = $this->replaceXmlFileConfig($res1,$search2,$replace2,false,true);
        $search3 = ['agents','agent','name="'.$post['number'].'@\\${domain}"','max-no-answer="[\s\S]*"'];
        $replace3 = ['agents','agent','name="'.$post['number'].'@${domain}"','max-no-answer="'.$post['max_no_answer'].'"'];
        $res3 = $this->replaceXmlFileConfig($res2,$search3,$replace3,false,true);
        $search4 = ['agents','agent','name="'.$post['number'].'@\\${domain}"','wrap-up-time="[\s\S]*"'];
        $replace4 = ['agents','agent','name="'.$post['number'].'@${domain}"','wrap-up-time="'.$post['wrap_up_time'].'"'];
        $res4 = $this->replaceXmlFileConfig($res3,$search4,$replace4,false,true);
        $search5 = ['agents','agent','name="'.$post['number'].'@\\${domain}"','reject-delay-time="[\s\S]*"'];
        $replace5 = ['agents','agent','name="'.$post['number'].'@${domain}"','reject-delay-time="'.$post['reject_delay_time'].'"'];
        $res5 = $this->replaceXmlFileConfig($res4,$search5,$replace5,false,true);
        $search6 = ['agents','agent','name="'.$post['number'].'@\\${domain}"','busy-delay-time="[\s\S]*"'];
        $replace6 = ['agents','agent','name="'.$post['number'].'@${domain}"','busy-delay-time="'.$post['busy_delay_time'].'"'];
        $res6 = $this->replaceXmlFileConfig($res5,$search6,$replace6,false,true);
        $search7 = ['tiers','tier','agent="'.$post['number'].'@\\${domain}"','level="[\s\S]*"'];
        $replace7 = ['tiers','tier','agent="'.$post['number'].'@${domain}"','level="'.$post['level'].'"'];
        $res7 = $this->replaceXmlFileConfig($res6,$search7,$replace7,false,true);
        $search8 = ['tiers','tier','agent="'.$post['number'].'@\\${domain}"','position="[\s\S]*"'];
        $replace8 = ['tiers','tier','agent="'.$post['number'].'@${domain}"','position="'.$post['position'].'"'];
        $res8 = $this->replaceXmlFileConfig($res7,$search8,$replace8,false,true);
        $this->writeToFile($file,$res8);
        return $res1&&$res2&&$res3&&$res4&&$res5&&$res6&&$res7&&$res8;
    }

    /**
     * 把freeswitch  中的配置注册到本地
     */
    public function actionRecoverZuoxi(){
        //以下命令是暂时的改变状态数据，运行reload mod_callcenter就会重新加载xml里面的数据，将数据恢复到默认值
        //命令是刷新freeswitch里面的status,max_no_answer,reject_delay_time的参数，命令中间用 逗号, 隔开
        $cmd1 = 'callcenter_config agent set status '.$_POST['number'].'@${domain} \''.$_POST['status'].'\',';
        $cmd2 = 'callcenter_config agent set type '.$_POST['number'].'@${domain} \''.$_POST['type'].'\',';
        $cmd3 = 'callcenter_config agent set max_no_answer '.$_POST['number'].'@${domain} \''.$_POST['max_no_answer'].'\',';
        $cmd4 = 'callcenter_config agent set wrap_up_time '.$_POST['number'].'@${domain} \''.$_POST['wrap_up_time'].'\',';
        $cmd5 = 'callcenter_config agent set reject_delay_time '.$_POST['number'].'@${domain} \''.$_POST['reject_delay_time'].'\',';
        $cmd6 = 'callcenter_config agent set busy_delay_time '.$_POST['number'].'@${domain} \''.$_POST['busy_delay_time'].'\',';
        $cmd7 = 'callcenter_config tier set level support@default '.$_POST['number'].'@${domain} \''.$_POST['level'].'\',';
        $cmd8 = 'callcenter_config tier set position support@default '.$_POST['number'].'@${domain} \''.$_POST['position'].'\',';
        $cmd = $cmd1.$cmd2.$cmd3.$cmd4.$cmd5.$cmd6.$cmd7.$cmd8;
        $this->execFSApi($cmd);
    }


    /**
     * 删除坐席的数据
     */
    public function actionDelete(){
        $id = $_POST['id'];
        $model = CtiZuoxi::findOne($id);
        $res = $model->delete();
        return $res;
    }

    /**
     * 坐席的电话号码的列表
     */
    public function actionList()
    {
        return $this->getList(new CtiZuoxi(),'','',['like','number',is_set($_POST,'zuoxi')]);
    }

    /**
     * 将坐席的数据导出到本地，格式为exel/csv
     * @param unknown $id
     */
    public function actionTemplateDownload()
    {
        try{
            $model = new CtiZuoxi();
            Excel::export([
                'models'=>$model,
                'fileName'=>time().'_zuoxi_template',
                'columns'=>[
                    '1',
                    '2',
                    '3',
                    '4',
                    '5',
                    '6',
                    '7',
                    '8',
                    '9',
                    '10',
                ],
                'headers'=>[
                    '1'=>'坐席名称',
                    '2'=>'坐席号码',
                    '3'=>'坐席类型',
                    '4'=>'坐席状态',
                    '5'=>'最大不回复时间',
                    '6'=>'最大包裹时间',
                    '7'=>'拒接后延迟时间',
                    '8'=>'忙后延迟时间',
                    '9'=>'等级',
                    '10'=>'位置',
                ]
            ]);
        }catch (\Exception $exception){
            Tools::l($exception);
        }

    }

    /**
     * 文件列表
     */
    public function actionFileList()
    {
        return $this->getFileList(new CtiFile(),"cti_zuoxi");
    }

    /**
     * freeswitch里面的动态注册呼叫中心
     * 修改conf/auto_configs/callcenter.conf.xml文件的内容
     * @return string
     */
    public function actionGetCallcenter(){
        $agents = '';//conf/auto_configs/callcenter.conf.xml文件里面的 <agents>配置
        $tiers = '';//conf/auto_configs/callcenter.conf.xml文件里面的 <tiers>配置
        $ctiZuoxi = CtiZuoxi::find()->select("*")->all();
        if (!empty($ctiZuoxi)){
            foreach ($ctiZuoxi as $k=>$v){
                $user = $v->number;
                $type = $v->type;
                $status = $v->status;
                $max_no_answer = $v->max_no_answer;
                $wrap_up_time = $v->wrap_up_time;
                $reject_delay_time = $v->reject_delay_time;
                $busy_delay_time = $v->busy_delay_time;
                $level = $v->level;
                $position = $v->position;
                $agents .= '    
  <agent name="'.$user.'@${domain}" type="'.$type.'" contact="[leg_timeout=10]user/'.$user.'@${domain}" status="'.$status.'" max-no-answer="'.$max_no_answer.'" wrap-up-time="'.$wrap_up_time.'" reject-delay-time="'.$reject_delay_time.'" busy-delay-time="'.$busy_delay_time.'" />';
                $tiers .= '
  <tier agent="'.$user.'@${domain}" queue="support@default" level="'.$level.'" position="'.$position.'"/>';
            }
        }
        //将conf/auto_configs/callcenter.conf.xml配置文件里面的内容替换掉，
        $res = $this->replaceXmlFileContents(ArrayHelper::toArray($this->remark),'/conf/autoload_configs/callcenter.conf.xml',['/<agents>([\s\S]*)<\/agents>/i','/<tiers>([\s\S]*)<\/tiers>/i'],['<agents>'.$agents.'</agents>','<tiers>'.$tiers.'</tiers>']);
        if ($res){
            $this->execFSBgapi("reload mod_callcenter");
            return json_encode(['data'=>'','res'=>$res]);
        }
        return json_encode(['data'=>'','res'=>$res]);
    }


}